<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>3_生命周期(新)</title>
</head>

<body>
<div id="test"></div>

<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

<script type="text/babel">
    //创建组件
    class Count extends React.Component {

        //构造器
        constructor(props) {
            super(props);
            console.log("constructor")
            this.state = {count: 0}
        }

        shouldComponentUpdate() {
            console.log("componentWillReceiveProps");
            return true;
        }

        //初始化渲染、状态更新之后
        render() {
            const {count} = this.state
            console.log("render")
            return (
                <div>
                    <h2>当前求和为{count}</h2>
                    <button onClick={this.add}>点我加1</button>
                    <button onClick={this.death}>卸载组件</button>
                    <button onClick={this.force}>不更改数据，强制更新</button>
                </div>
            )
        }

        //若state的值在任何时候都取决于props，那么可以使用getDerivedStateFromProps
        static getDerivedStateFromProps(props) {
            console.log("getDerivedStateFromProps", props);
            return null;
        }

        getSnapshotBeforeUpdate() {
            console.log("getSnapshotBeforeUpdate");
            return "snapshotValue:boy";
        }

        //组件挂载完毕的勾子
        componentDidMount() {
            console.log("componentDidMount");
        }

        //组件已经更新的勾子
        componentDidUpdate(preProps,preState,snapshotValue) {
            console.log("componentDidUpdate",preProps,preState,snapshotValue);
        }

        //数据加一按钮的回调
        add = () => {
            //获取原来状态
            const {count} = this.state;
            //状态+1
            this.setState({count: count + 1});
        }

        //卸载组件按钮的回调
        death = () => {
            ReactDOM.unmountComponentAtNode(document.getElementById('test'));

        }

        //强制更新按钮的回调
        force = () => {
            this.forceUpdate();
        }

    }

    //渲染组件
    ReactDOM.render(<Count count={100}/>, document.getElementById('test'));

</script>
</body>

</html>
